import 'dart:collection';

import 'package:flutter/material.dart';

class RouterObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    RouterHelper().curRoute = route;
    RouterHelper()._push(route, previousRoute);
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    if (oldRoute != null) {
      RouterHelper()._pop(oldRoute, null);
    }
    if (newRoute != null) {
      RouterHelper().curRoute = newRoute;
      RouterHelper()._push(newRoute, oldRoute);
    }
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    RouterHelper()._pop(route, previousRoute);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) async {
    RouterHelper().curRoute = previousRoute;
    RouterHelper()._pop(route, previousRoute);
  }
}

class RouterHelper {
  factory RouterHelper() {
    _singleton ??= RouterHelper._();
    return _singleton!;
  }

  static RouterHelper? _singleton;

  final RouterObserver observer = RouterObserver();

  late Queue<Route<dynamic>> routeQueue;
  Route<dynamic>? curRoute;

  RouterHelper._() {
    routeQueue = DoubleLinkedQueue();
  }

  void _push(Route<dynamic> route, Route<dynamic>? previousRoute) {
    routeQueue.add(route);
  }

  void _pop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    routeQueue.remove(route);
  }

  bool containPage(String name) {
    for (var route in routeQueue) {
      if (route.settings.name == name) {
        return true;
      }
    }
    return false;
  }
}
